import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/entity/login_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/system_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/utils/verify_utils.dart';
import 'package:nyh_motorcade_app/widgets/loading_dialog.dart';

class PhoneLoginController extends GetxController {
  FocusNode phoneFocus = FocusNode();
  FocusNode verityCodeFocus = FocusNode();

  String phone = "";
  String verityCode = "";

  Timer? timer;
  int currentTime = 0;

  void setPhone(String phone) {
    this.phone = phone;
    update();
  }

  void setVerityCode(String verityCode) {
    this.verityCode = verityCode;
    update();
  }

  void getVerifyCode() {
    if (phone.isEmpty) {
      ToastUtils.toast("请输入手机号");
      return;
    }
    if (!VerifyUtils.isPhone(phone)) {
      ToastUtils.toast("手机号格式不正确");
      return;
    }

    phoneFocus.unfocus();

    httpManager.post(
      Get.context,
      HttpAddress.GET_VERIFY_CODE,
      {
        "loginPhone": phone,
      },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        ToastUtils.toast("验证码已发送");
        _countdown();
      },
    );
  }

  void _countdown() {
    currentTime = 1;
    update();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (currentTime < 60) {
        currentTime++;
      } else {
        cancelTimer();
      }
      update();
    });
  }

  Future<void> login() async {
    if (phone.isEmpty || verityCode.isEmpty) {
      return;
    }
    if (!VerifyUtils.isPhone(phone)) {
      ToastUtils.toast("手机号格式不正确");
      return;
    }
    if (verityCode.length != 6) {
      ToastUtils.toast("请输入6位数的验证码");
      return;
    }

    phoneFocus.unfocus();
    verityCodeFocus.unfocus();

    SPUtils.saveString(SPUtils.TOKEN, "");
    SPUtils.saveString(SPUtils.COMPANY_ID, "");

    httpManager.post(
      Get.context,
      HttpAddress.LOGIN_BY_VERIFY_CODE,
      {
        "oilEngineNo": await SystemUtils.getDeviceId(),
        "loginPhone": phone,
        "code": verityCode,
      },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("登录失败");
          return;
        }
        LoginEntity loginEntity = LoginEntity().fromJson(data);
        String? token = loginEntity.token ?? "";
        if (token.isEmpty) {
          ToastUtils.toast("token为空");
          return;
        }
        SPUtils.saveString(SPUtils.TOKEN, token);
        SPUtils.saveBool(SPUtils.IS_ADMIN, loginEntity.isAdmin ?? false);
        getCompanyList();
      },
    );
  }

  Future<void> getCompanyList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_LIST,
      {},
      isToast: true,
      onSuccess: (data) {
        LoadingDialog.dismissDialog(Get.context);
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is List) {
          List<CompanyEntity> companyList = data.map((element) {
            return CompanyEntity().fromJson((element as Map<String, dynamic>));
          }).toList();
          if (companyList.isEmpty) {
            ToastUtils.toast("您没有用油客户权限,请联系管理员");
            return;
          }
          cancelTimer();
          SPUtils.saveString(SPUtils.COMPANY_ID, companyList.first.id ?? "");
          Get.offNamedUntil(Routes.main, (route) => false, arguments: companyList);
        }
      },
      onFail: (code, msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
      onError: (msg) {
        LoadingDialog.dismissDialog(Get.context);
      },
    );
  }

  @override
  void onClose() {
    super.onClose();
    cancelTimer();
  }

  void cancelTimer() {
    if (timer != null) {
      currentTime = 0;
      timer!.cancel();
    }
  }
}
